package com.ruoyi.questionnaire.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.questionnaire.domain.QuestionnaireAnswer;
import com.ruoyi.questionnaire.domain.QuestionnaireAnswerDetail;
import com.ruoyi.questionnaire.domain.QuestionnaireAnswerSubmitDTO;
import com.ruoyi.questionnaire.domain.QuestionnaireAnswerVO;
import com.ruoyi.questionnaire.domain.QuestionnaireOption;
import com.ruoyi.questionnaire.domain.QuestionnaireQuestion;
import com.ruoyi.questionnaire.mapper.QuestionnaireAnswerMapper;
import com.ruoyi.questionnaire.service.IQuestionnaireAnswerDetailService;
import com.ruoyi.questionnaire.service.IQuestionnaireAnswerService;
import com.ruoyi.questionnaire.service.IQuestionnaireOptionService;
import com.ruoyi.questionnaire.service.IQuestionnaireQuestionService;
import com.ruoyi.questionnaire.util.SnowflakeIdUtil;

/**
 * 问卷答卷Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@Service
public class QuestionnaireAnswerServiceImpl implements IQuestionnaireAnswerService 
{
    @Autowired
    private QuestionnaireAnswerMapper answerMapper;
    
    @Autowired
    private IQuestionnaireAnswerDetailService answerDetailService;

    @Autowired
    private IQuestionnaireQuestionService questionService;
    @Autowired
    private IQuestionnaireOptionService optionService;

    /**
     * 查询问卷答卷
     * 
     * @param id 问卷答卷主键
     * @return 问卷答卷
     */
    @Override
    public QuestionnaireAnswer selectQuestionnaireAnswerById(Long id)
    {
        return answerMapper.selectQuestionnaireAnswerById(id);
    }

    /**
     * 查询问卷答卷列表
     * 
     * @param questionnaireAnswer 问卷答卷
     * @return 问卷答卷
     */
    @Override
    public List<QuestionnaireAnswer> selectQuestionnaireAnswerList(QuestionnaireAnswer questionnaireAnswer)
    {
        return answerMapper.selectQuestionnaireAnswerList(questionnaireAnswer);
    }

    /**
     * 查询问卷答卷VO列表（包含问卷标题和用户信息）
     * 
     * @param questionnaireAnswer 问卷答卷
     * @return 问卷答卷VO集合
     */
    @Override
    public List<QuestionnaireAnswerVO> selectQuestionnaireAnswerVOList(QuestionnaireAnswer questionnaireAnswer)
    {
        List<QuestionnaireAnswerVO> voList = answerMapper.selectQuestionnaireAnswerVOList(questionnaireAnswer);
        if (voList != null && !voList.isEmpty()) {
            for (QuestionnaireAnswerVO vo : voList) {
                List<QuestionnaireAnswerDetail> details = answerDetailService.selectAnswerDetailList(vo.getId());
                for (QuestionnaireAnswerDetail detail : details) {
                    QuestionnaireQuestion question = questionService.selectQuestionnaireQuestionById(detail.getQuestionId());
                    detail.setQuestionTitle(question != null ? question.getContent() : "");
                    if (question != null && ("single".equals(question.getQuestionType()) || "multiple".equals(question.getQuestionType()))) {
                        List<QuestionnaireOption> options = optionService.selectQuestionnaireOptionList(detail.getQuestionId());
                        Map<String, String> valueLabelMap = new HashMap<>();
                        for (QuestionnaireOption opt : options) {
                            valueLabelMap.put(opt.getOptionValue(), opt.getOptionLabel());
                        }
                        if ("multiple".equals(question.getQuestionType())) {
                            String[] values = detail.getOptionValue() != null ? detail.getOptionValue().split(",") : new String[0];
                            StringBuilder labelBuilder = new StringBuilder();
                            for (String v : values) {
                                if (labelBuilder.length() > 0) labelBuilder.append(", ");
                                labelBuilder.append(valueLabelMap.getOrDefault(v, v));
                            }
                            detail.setOptionLabel(labelBuilder.toString());
                        } else {
                            detail.setOptionLabel(valueLabelMap.getOrDefault(detail.getOptionValue(), detail.getOptionValue()));
                        }
                    } else {
                        detail.setOptionLabel(detail.getOptionValue());
                    }
                }
                vo.setDetails(details);
            }
        }
        return voList;
    }

    /**
     * 新增问卷答卷
     * 
     * @param questionnaireAnswer 问卷答卷
     * @return 结果
     */
    @Override
    public int insertQuestionnaireAnswer(QuestionnaireAnswer answer) {
        answer.setSubmitTime(new Date());
        return answerMapper.insertQuestionnaireAnswer(answer);
    }

    /**
     * 修改问卷答卷
     * 
     * @param questionnaireAnswer 问卷答卷
     * @return 结果
     */
    @Override
    public int updateQuestionnaireAnswer(QuestionnaireAnswer questionnaireAnswer)
    {
        return answerMapper.updateQuestionnaireAnswer(questionnaireAnswer);
    }

    /**
     * 批量删除问卷答卷
     * 
     * @param ids 需要删除的问卷答卷主键
     * @return 结果
     */
    @Override
    public int deleteQuestionnaireAnswerByIds(Long[] ids)
    {
        return answerMapper.deleteQuestionnaireAnswerByIds(ids);
    }

    /**
     * 删除问卷答卷信息
     * 
     * @param id 问卷答卷主键
     * @return 结果
     */
    @Override
    public int deleteQuestionnaireAnswerById(Long id)
    {
        return answerMapper.deleteQuestionnaireAnswerById(id);
    }

    /**
     * 根据问卷ID查询答案列表
     * 
     * @param questionnaireId 问卷ID
     * @return 答案列表
     */
    @Override
    public List<QuestionnaireAnswer> selectAnswersByQuestionnaireId(Long questionnaireId)
    {
        QuestionnaireAnswer query = new QuestionnaireAnswer();
        query.setQuestionnaireId(questionnaireId);
        return answerMapper.selectQuestionnaireAnswerList(query);
    }

    /**
     * 提交问卷答卷
     * 
     * @param questionnaireAnswer 问卷答卷
     * @return 结果
     */
    @Override
    public int submitQuestionnaireAnswer(QuestionnaireAnswer questionnaireAnswer)
    {
        if (questionnaireAnswer.getId() == null) {
            questionnaireAnswer.setId(SnowflakeIdUtil.nextId());
        }
        questionnaireAnswer.setSubmitTime(new Date());
        
        // 插入答卷主表
        int result = answerMapper.insertQuestionnaireAnswer(questionnaireAnswer);
        
        return result;
    }

    /**
     * 提交问卷答卷（新方法，支持答案详情）
     * 
     * @param submitDTO 问卷答案提交DTO
     * @return 结果
     */
    @Override
    @Transactional
    public int submitQuestionnaireAnswerWithDetails(QuestionnaireAnswerSubmitDTO submitDTO)
    {
        // 1. 创建答卷主记录
        QuestionnaireAnswer answer = new QuestionnaireAnswer();
        answer.setQuestionnaireId(submitDTO.getQuestionnaireId());
        answer.setUserId(submitDTO.getUserId());
        answer.setSubmitTime(new Date());
        if (answer.getId() == null) {
            answer.setId(SnowflakeIdUtil.nextId());
        }
        
        // 2. 插入答卷主表
        int result = answerMapper.insertQuestionnaireAnswer(answer);
        if (result <= 0) {
            throw new RuntimeException("插入答卷主表失败");
        }
        
        // 3. 插入答案详情
        if (submitDTO.getDetails() != null && !submitDTO.getDetails().isEmpty()) {
            for (QuestionnaireAnswerSubmitDTO.AnswerDetailDTO detailDTO : submitDTO.getDetails()) {
                QuestionnaireAnswerDetail detail = new QuestionnaireAnswerDetail();
                detail.setAnswerId(answer.getId());
                detail.setQuestionId(detailDTO.getQuestionId());
                detail.setOptionValue(detailDTO.getOptionValue());
                if (detail.getId() == null) {
                    detail.setId(SnowflakeIdUtil.nextId());
                }
                answerDetailService.insertAnswerDetail(detail);
            }
        }
        
        return result;
    }

    @Override
    public int countByUserId(Long userId) {
        return answerMapper.countByUserId(userId);
    }

    /**
     * 查询单个答卷VO（含详情）
     */
    public QuestionnaireAnswerVO selectQuestionnaireAnswerVOById(Long id) {
        List<QuestionnaireAnswerVO> list = selectQuestionnaireAnswerVOList(new QuestionnaireAnswer() {{ setId(id); }});
        return (list != null && !list.isEmpty()) ? list.get(0) : null;
    }
} 